/*
Title:                  IV functions
Project:                Medellin Gang Governance
Authors:                Zach
Date Created:           Sept 27, 2019
Description:            This .do file provides a function used in the analysis code
*/
********************************************************************************
* Define the analysis function ************************************************
********************************************************************************

cap program drop vert_parm_reg
program define vert_parm_reg
    set matsize 10000
    syntax  [if/], outcomevars(namelist)  FILENAME(name) [fixedeffects(varlist) controls(varlist)]

    cap mat drop results
    cap mat drop stars

    if "`fixedeffects'"!="" local vfe abs(`fixedeffects')
    if "`fixedeffects'"=="" local vfe noa

    local ifa if `if'
    local rownum = `: word count `outcomevars''

    mat define results     = J(`rownum',18, .)
    mat define stars       = J(`rownum',18, 0)

    local i = 0
    local loutcomevars
    /* Set restrictions for short and long term surveys */
    foreach y in `outcomevars' {

        local if_control_mean `if' & control
        if(regexm("`y'", "death")) local if_control_mean control


        local ++i
        local loutcomevars `loutcomevars' `y'_tyav
        /* Loop over short term and long term */
            /* Get treatment means mean */
            qui sum `y'_tyav  if `if_control_mean'
                mat results[`i',1] = r(mean)
                mat results[`i',2] = r(sd)
            if `r(N)' {
                    /* Run regression */
                    qui reghdfe `y'_tyav tpassonly cashassonly tpcashass `controls' `ifa', vce(r) `vfe'
*                    mat results[`i',1 ] = e(N)

                        /* Recover Coefficients, standard errors, and p-values */

                        mat results[`i',4] = _b[tpassonly]
                        mat results[`i',5] = _se[tpassonly]
                        mat results[`i',6] = 2*ttail(e(df_r),abs(_b[tpassonly]/_se[tpassonly]))

                        mat results[`i',7]= _b[cashassonly]
                        mat results[`i',8]= _se[cashassonly]
                        mat results[`i',9]= 2*ttail(e(df_r),abs(_b[cashassonly]/_se[cashassonly]))

                        mat results[`i',10]= _b[tpcashass]
                        mat results[`i',11]= _se[tpcashass]
                        mat results[`i',12]= 2*ttail(e(df_r),abs(_b[tpcashass]/_se[tpcashass]))

                        mat results[`i',13] =  _b[tpcashass] - _b[tpassonly]
                         qui test tpcashass - tpassonly = 0
                        mat results[`i',14] = r(p)

                        mat results[`i',16] =  _b[tpcashass] - _b[cashassonly]
                         qui test tpcashass - cashassonly = 0
                        mat results[`i',17] = r(p)


            local colcount = 0
            foreach tcount in tpassonly cashassonly tpcashass{
               mat stars[`i',4 + `colcount']      = cond(results[`i', 6 + `colcount'] <= .01,3, ///
                                                    cond(results[`i', 6 + `colcount'] <= .05,2, ///
                                                    cond(results[`i', 6 + `colcount'] <= .1,1,0  ///
               )))
               local colcount = `colcount' + 3
            }

   local colcount = 0
            foreach tcount in tpovstpc caovstpc{
               mat stars[`i',13 + `colcount']      = cond(results[`i',14 + `colcount'] <= .01,3, ///
                                                     cond(results[`i',14 + `colcount'] <= .05,2, ///
                                                     cond(results[`i',14 + `colcount'] <= .1,1,0  ///
               )))
               local colcount = `colcount' + 3
            }


            }
            }

    local label9y  `" "" "\uline{\hfill Average Treatment Effects \hfill}", "", "", "\uline{\hfill Differences \hfill}", "" "'
    local tlabel9y `" "\thead{Control \\ Mean}","\thead{Therapy \\ Only}","\thead{Cash \\ Only}","\thead{Both}","\thead{Therapy Only \\ vs Both}","\thead{Cash Only \\ vs Both}" "'
    local clabel9y `" "","\thead{Estimate \\ (SE) \\{} [p-value]}","\thead{Estimate \\ (SE) \\{} [p-value]}","\thead{Estimate \\ (SE) \\{} [p-value]}", "\thead{Estimate \\{} [p-value]}","\thead{Estimate \\{} [p-value]}" "'
    local nlabel9y `" "(1)","(2)","(3)","(4)","(5)","(6)" "'
    local ndecimal9y  3,3,3,3,3,3,

matrix rownames results = `loutcomevars'

     frmttable, statmat(results) sdec(`ndecimal9y') substat(2)
     qui frmttable, statmat(results) varlabels substat(2) sdec(`ndecimal9y')  annotate(stars) asymbol(*,**,***)

frmttable using outfiles/tables/`filename', ///
ctitle(" ",  `label9y'  \ " " , `tlabel9y' \ " ",`clabel9y'  \  "",`nlabel9y' ) ///
tex fragment replace nocenter squarebrack ///
multicol(1,3,3;1,6,2)




    end








cap program drop inter_covar_treat_reg
program define inter_covar_treat_reg
    set matsize 10000
    syntax  [if/], outcomevar(namelist)  FILENAME(name) label_first_row(string) controls(varlist)  [fixedeffects(varlist) add_ftest(string)]


   cap drop levels_var
   gen levels_var = .
   label var levels_var `label_first_row'

    cap mat drop results
    cap mat drop stars

    if "`fixedeffects'"!="" local vfe abs(`fixedeffects')
    if "`fixedeffects'"=="" local vfe noa

    local ifa if `if'
    local rownum = `: word count `controls'' + 1
   *We are adding one to have space for the levels

    mat define results     = J(`rownum',21, .)
    mat define stars       = J(`rownum',21, 0)

    local i = 1
     foreach c in `controls' {
        local ++i
            /* Get control sample means */
            qui sum `c'  if `if'
                mat results[`i',1] = r(mean)
                mat results[`i',2] = r(sd)

                            }


***CREATE INTERACTION TERMS***


    global inter_covars_all

foreach treat in tpassonly cashassonly tpcashass {

        foreach c in `controls' {

                 cap drop `treat'_`c'
                 gen `treat'_`c' = `treat' * `c'
                 global inter_covars_all         $inter_covars_all         `treat'_`c'

                                }

}


   global inter_covars_tpassonly
   global inter_covars_cashassonly
   global inter_covars_tpcashass

        foreach c in `controls' {

   global inter_covars_tpassonly   $inter_covars_tpassonly     tpassonly_`c'
   global inter_covars_cashassonly $inter_covars_cashassonly cashassonly_`c'
   global inter_covars_tpcashass   $inter_covars_tpcashass     tpcashass_`c'


}



***RUN REGRESSION
                     reghdfe `outcomevar' tpassonly cashassonly tpcashass `controls' ///
                    $inter_covars_all   `ifa', vce(r) `vfe'


****MAKE MATRIX
                        /* Recover Coefficients, standard errors, and p-values */
    local i = 1

                        mat results[`i',7] = _b[tpassonly]
                        mat results[`i',8] = _se[tpassonly]
                        mat results[`i',9] = 2*ttail(e(df_r),abs(_b[tpassonly]/_se[tpassonly]))

                        mat results[`i',10]= _b[cashassonly]
                        mat results[`i',11]= _se[cashassonly]
                        mat results[`i',12]= 2*ttail(e(df_r),abs(_b[cashassonly]/_se[cashassonly]))

                        mat results[`i',13]= _b[tpcashass]
                        mat results[`i',14]= _se[tpcashass]
                        mat results[`i',15]= 2*ttail(e(df_r),abs(_b[tpcashass]/_se[tpcashass]))

                        mat results[`i',16] =  _b[tpcashass] - _b[tpassonly]
                         qui test tpcashass - tpassonly = 0
                        mat results[`i',17] = r(p)

                        mat results[`i',19] =  _b[tpcashass] - _b[cashassonly]
                         qui test tpcashass - cashassonly = 0
                        mat results[`i',20] = r(p)


    local i = 2
     foreach c in `controls' {

                        mat results[`i',4] = _b[`c']
                        mat results[`i',5] = _se[`c']
                        mat results[`i',6] = 2*ttail(e(df_r),abs(_b[`c']/_se[`c']))

                        mat results[`i',7] = _b[tpassonly_`c']
                        mat results[`i',8] = _se[tpassonly_`c']
                        mat results[`i',9] = 2*ttail(e(df_r),abs(_b[tpassonly_`c']/_se[tpassonly_`c']))

                        mat results[`i',10]= _b[cashassonly_`c']
                        mat results[`i',11]= _se[cashassonly_`c']
                        mat results[`i',12]= 2*ttail(e(df_r),abs(_b[cashassonly_`c']/_se[cashassonly_`c']))

                        mat results[`i',13]= _b[tpcashass_`c']
                        mat results[`i',14]= _se[tpcashass_`c']
                        mat results[`i',15]= 2*ttail(e(df_r),abs(_b[tpcashass_`c']/_se[tpcashass_`c']))

                        mat results[`i',16] =  _b[tpcashass_`c'] - _b[tpassonly_`c']
                         qui test tpcashass - tpassonly = 0
                        mat results[`i',17] = r(p)

                        mat results[`i',19] =  _b[tpcashass_`c'] - _b[cashassonly_`c']
                         qui test tpcashass - cashassonly = 0
                        mat results[`i',20] = r(p)

        local ++i

}

***PROFIT

       local i = 1
     foreach c in my_levels `controls' {


            local colcount = 0
            foreach tcount in covar tpassonly cashassonly tpcashass{
               mat stars[`i',4 + `colcount']      = cond(results[`i', 6 + `colcount'] <= .01,3, ///
                                                    cond(results[`i', 6 + `colcount'] <= .05,2, ///
                                                    cond(results[`i', 6 + `colcount'] <= .1,1,0  ///
               )))
               local colcount = `colcount' + 3
            }

   local colcount = 0
            foreach tcount in tpovstpc caovstpc{
               mat stars[`i',16 + `colcount']      = cond(results[`i',17 + `colcount'] <= .01,3, ///
                                                     cond(results[`i',17 + `colcount'] <= .05,2, ///
                                                     cond(results[`i',17 + `colcount'] <= .1,1,0  ///
               )))
               local colcount = `colcount' + 3
            }

        local ++i
}


    local label9y  `" "" "" "\uline{\hfill Interaction Coeff. \hfill}", "", "", "\uline{\hfill Differences \hfill}", "" "'
    local tlabel9y `" "\thead{Sample \\ Mean}",  "\thead{Control}",  "\thead{Therapy \\ Only}","\thead{Cash \\ Only}","\thead{Both}","\thead{Therapy Only \\ vs Both}","\thead{Cash Only \\ vs Both}" "'
    local clabel9y `" "","\thead{Estimate \\ (SE) \\{} [p-value]}","\thead{Estimate \\ (SE) \\{} [p-value]}","\thead{Estimate \\ (SE) \\{} [p-value]}","\thead{Estimate \\ (SE) \\{} [p-value]}", "\thead{Estimate \\{} [p-value]}","\thead{Estimate \\{} [p-value]}" "'
    local nlabel9y `" "(1)","(2)","(3)","(4)","(5)","(6)", "(7)" "'
    local ndecimal9y  3,3,3,3,3,3,3,


    if "`add_ftest'" == "yes" {

  qui test `controls'

        local ftest_control   = round(r(p), 0.001)

  qui test $inter_covars_tpassonly

        local ftest_therapy   = round(r(p), 0.001)

  qui test $inter_covars_cashassonly

        local ftest_cash      = round(r(p), 0.001)

  qui test $inter_covars_tpcashass

        local ftest_both      = round(r(p), 0.001)

        local my_ftest_row addrows("Joint F-Test" "" "`ftest_control'" "`ftest_therapy'" "`ftest_cash'" "`ftest_both'" "" "")

        }

matrix rownames results = levels_var `controls'

     frmttable, statmat(results) sdec(`ndecimal9y') substat(2)
     qui frmttable, statmat(results) varlabels substat(2) sdec(`ndecimal9y')  annotate(stars) asymbol(*,**,***)

frmttable using outfiles/tables/`filename', ///
ctitle(" ",  `label9y'  \ " " , `tlabel9y' \ " ",`clabel9y'  \  "",`nlabel9y' ) ///
tex fragment replace nocenter squarebrack ///
multicol(1,4,3;1,7,2) ///
`my_ftest_row'


    end
